import 'dart:math';

import 'package:valovault_reminder/common/ui/val_auto_fit_screen_size.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'val_ui_kit_btn.dart';
import 'val_ui_kit_base_colors.dart';
import 'val_ui_kit_fast_element.dart';
import 'val_ui_kit_base_decoration.dart';
import 'val_ui_kit_dialog.dart';
import 'val_fast_string_tool.dart';
import 'val_common_text.dart';

class ValUIKitDialogImpl {
  static get _getContext => Get.overlayContext!;
  static const String tagLogin = "tagLogin";
  static const String tagShowAuthFail = "tagShowAuthFail";
  static const String tagShowAuthBlack = "tagShowAuthBlack";
  static const String tagNetError = "tagNetError";
  static const String tagMessageAttach = "tag_message_attach";
  static const String tagAspirationAttach = "tag_aspiration_attach";
  static const String tagImItemAttach = "tag_im_item_attach";
  static const String tagGPTItemAttach = "tag_im_item_attach";
  static const String tagImEmojiItemAttach = "tag_im_emoji_item_attach";
  static const String tagCollectionAttach = "tag_collection_attach";

  ///显示进度对话框
  static void showProgress({bool? barrierDismissible = false, ValueNotifier<double>? progress}) {
    ValUIKitDialog.showProgress(_getContext, barrierDismissible: barrierDismissible, progress: progress);
  }

  ///关闭进度对话框
  static void hideProgress({bool needHideKeyboard = false}) {
    if (needHideKeyboard) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
    ValUIKitDialog.hideProgress(_getContext);
  }

  ///关闭dialog
  static void closeDialog({
    bool barrierDismissible = false,
    String? tag,
    RouteTransitionsBuilder? transitionBuilder,
    Duration? transitionDuration,
    Color barrierColor = Colors.black54,
  }) {
    ValUIKitDialog.closeDialog(_getContext);
  }

  static void showOneBtn({
    required String title,
    required String msg,
    required String btn,
    required Function() onTap,
    Widget? msgWidget,
    bool barrierDismissible = false,
    String? tag,
    RouteTransitionsBuilder? transitionBuilder,
    Duration? transitionDuration,
    Color barrierColor = Colors.black54,
  }) {
    showCenter(
      CenterDialog(
        title: title,
        msg: msg,
        msgWidget: msgWidget,
        btnPositive: btn,
        onTapPositive: onTap,
      ),
      barrierDismissible: barrierDismissible,
      transitionBuilder: transitionBuilder,
      tag: tag,
      transitionDuration: transitionDuration,
      barrierColor: barrierColor,
    );
  }

  static Future showTowBtn(
      {required String msg,
        required Function() onTapPositive,
        String btnPositive = 'Sure',
        String title = "Tip",
        String btnNegative = "Cancel",
        Function()? onTapNegative,
        Widget? msgWidget,
        bool barrierDismissible = false,
        String? tag,
        RouteTransitionsBuilder? transitionBuilder,
        Duration? transitionDuration,
        Color barrierColor = Colors.black54,
        EdgeInsets? dialogMargin,
        EdgeInsets? msgPadding,
        EdgeInsets? titlePadding}) {
    return showCenter(
      CenterDialog(
        title: title,
        msg: msg,
        msgWidget: msgWidget,
        btnPositive: btnPositive,
        onTapPositive: onTapPositive,
        btnNegative: btnNegative,
        onTapNegative: onTapNegative ?? () => closeDialog(),
        dialogMargin: dialogMargin,
        msgPadding: msgPadding,
        titlePadding: titlePadding,
      ),
      barrierDismissible: barrierDismissible,
      transitionBuilder: transitionBuilder,
      tag: tag,
      transitionDuration: transitionDuration,
      barrierColor: barrierColor,
    );
  }

  static Future showNoBtn(
      {String title = "提示",
        required String msg,
        Widget? msgWidget,
        bool barrierDismissible = true,
        String? tag,
        RouteTransitionsBuilder? transitionBuilder,
        Duration? transitionDuration,
        Color barrierColor = Colors.black54,
        EdgeInsets? dialogMargin,
        EdgeInsets? msgPadding,
        EdgeInsets? titlePadding}) {
    return showCenter(
      CenterDialog(
        title: title,
        msg: msg,
        msgWidget: msgWidget,
        dialogMargin: dialogMargin,
        msgPadding: msgPadding,
        titlePadding: titlePadding,
      ),
      barrierDismissible: barrierDismissible,
      transitionBuilder: transitionBuilder,
      tag: tag,
      transitionDuration: transitionDuration,
      barrierColor: barrierColor,
    );
  }

  ///显示中间的一个
  static Future showCenter(
      Widget content, {
        bool barrierDismissible = false,
        String? tag,
        RouteTransitionsBuilder? transitionBuilder,
        Duration? transitionDuration,
        Color barrierColor = Colors.black54,
      }) =>
      ValUIKitDialog.showCenter(
        _getContext,
        content,
        barrierDismissible: barrierDismissible,
        transitionBuilder: transitionBuilder,
        tag: tag,
        transitionDuration: transitionDuration,
        barrierColor: barrierColor,
      );

  static void showNetErr(String msg) {
    // showOneBtn(
    //   title: "请求失败",
    //   msg: msg,
    //   btn: "取消",
    //   onTap: () => closeDialog(),
    // );
  }

  static Future hideAttach({String? tag}) async => await SmartDialog.dismiss(status: SmartStatus.attach, tag: tag);
}

class CenterDialog extends StatelessWidget {
  const CenterDialog(
      {super.key,
        this.title = "",
        this.titleWidget,
        this.msg = "",
        this.msgWidget,
        this.btnPositive = "",
        this.onTapPositive,
        this.btnPositiveWidget,
        this.btnNegative = "",
        this.onTapNegative,
        this.btnNegativeWidget,
        this.titlePadding,
        this.msgPadding,
        this.dialogMargin});

  final String title;
  final Widget? titleWidget;
  final String msg;
  final Widget? msgWidget;
  final String btnPositive;
  final Function()? onTapPositive;
  final Widget? btnPositiveWidget;
  final String btnNegative;
  final Function()? onTapNegative;
  final Widget? btnNegativeWidget;
  final EdgeInsets? titlePadding;
  final EdgeInsets? msgPadding;
  final EdgeInsets? dialogMargin;

  @override
  Widget build(BuildContext context) {
    var children = <Widget>[];
    Widget t = ValCommonText.oneLineBold(
      title,
      17,
      ValUIKitBaseColors.textLeveOne,
    );
    if (titleWidget != null) {
      t = titleWidget!;
    }
    children.add(Padding(
      padding: titlePadding ?? EdgeInsets.fromLTRB(24.w, 24.w, 24.w, 28.w),
      child: t,
    ));

    Widget m = ValCommonText.moreLine(
      msg,
      16,
      ValUIKitBaseColors.textLeveOne,
    );
    if (msgWidget != null) {
      m = msgWidget!;
    }
    children.add(Padding(
      padding: msgPadding ?? EdgeInsets.fromLTRB(24.w, 0, 24.w, 28.w),
      child: m,
    ));

    if (btnNegative.isNotEmpty || btnNegativeWidget != null || btnPositive.isNotEmpty || btnPositiveWidget != null) {
      children.add(ValUIKitBaseDivider(
        height: 1.w,
      ));
    }

    var cl = <Widget>[];
    if (btnNegative.isNotEmpty || btnNegativeWidget != null) {
      Widget bn = ValCommonText.oneLine(btnNegative, 17, ValUIKitBaseColors.textLeveOne);
      if (btnNegativeWidget != null) {
        bn = btnNegativeWidget!;
      }
      bn = ValUIKitBtn.item(
        bn,
        onTapNegative!,
        alignment: Alignment.center,
        height: 50.w,
      );
      cl.add(Expanded(child: bn));
      cl.add(Container(
        color: ValUIKitBaseColors.line,
        width: 1.w,
        height: 50.w,
      ));
    }

    if (btnPositive.isNotEmpty || btnPositiveWidget != null) {
      Widget bn = ValCommonText.oneLine(btnPositive, 17, ValUIKitBaseColors.theme);
      if (btnPositiveWidget != null) {
        bn = btnPositiveWidget!;
      }
      bn = ValUIKitBtn.item(
        bn,
        onTapPositive!,
        alignment: Alignment.center,
        height: 50.w,
      );
      cl.add(Expanded(child: bn));

      children.add(Row(children: cl));
    }

    return CommonDialogCenterScaffold(
      margin: dialogMargin,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: children,
      ),
    );
  }
}

class CommonDialogCenterScaffold extends StatelessWidget {
  const CommonDialogCenterScaffold({required this.child, required this.margin, Key? key}) : super(key: key);

  final Widget child;
  final EdgeInsets? margin;

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.center,
      child: Material(
        color: Colors.transparent,
        child: Container(
          margin: margin ?? EdgeInsets.symmetric(horizontal: 40.w),
          decoration: ValUIKitBaseDecoration.getShapeDecoration(
            radius: 6.w,
            bg: ValUIKitBaseColors.white,
          ),
          child: child,
        ),
      ),
    );
  }
}

class CommonDialogBottomScaffold extends StatelessWidget {
  const CommonDialogBottomScaffold({
    required this.child,
    this.padding,
    Key? key,
  }) : super(key: key);

  final Widget child;
  final EdgeInsets? padding;

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Material(
        color: Colors.transparent,
        child: Container(
          width: double.maxFinite,
          decoration: ValUIKitBaseDecoration.getRadius(
            topLeft: 10.w,
            topRight: 10.w,
            bg: ValUIKitBaseColors.white,
          ),
          padding: padding ??
              ValAutoFitScreenSize.compatibleBottom(
                padding: EdgeInsets.only(bottom: 10.w),
              ),
          child: child,
        ),
      ),
    );
  }
}

class BottomActionDialog extends StatelessWidget {
  const BottomActionDialog({
    required this.actions,
    this.title,
    Key? key,
  }) : super(key: key);

  final String? title;
  final List<Widget> actions;

  @override
  Widget build(BuildContext context) {
    return CommonDialogBottomScaffold(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          CommonMargin.height(10.w),
          if (ValFastStringTool.isNotEmpty(title))
            Padding(
              padding: EdgeInsets.only(top: 6.w, bottom: 8.w),
              child: ValCommonText.oneLine(title!, 14.w, ValUIKitBaseColors.black, fontWeight:  FontWeight.bold,),
            ),
          ...actions,
          _builtCancelBtn(),
        ],
      ),
    );
  }

  ///取消
  Widget _builtCancelBtn() {
    return Padding(
      padding: EdgeInsets.fromLTRB(16.w, 10.w, 16.w, 0),
      child: ValUIKitBtn.shape(
        const ValCommonText.oneLine('取消', 16, ValUIKitBaseColors.textLeveOne, leading: 0),
        ValUIKitDialogImpl.closeDialog,
        alignment: Alignment.center,
        height: 44.w,
        bg: ValUIKitBaseColors.whiteF6,
        hasInkWell: false,
      ),
    );
  }

  static Widget btn(String t, Function() onTap, {Color? textColor, Widget? icon}) {
    Widget child = ValCommonText.oneLine(t, 16, textColor ?? ValUIKitBaseColors.textLeveOne, forceStrutHeight: false);
    if (icon != null) {
      child = Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          icon,
          CommonMargin.width(8.w),
          child,
        ],
      );
    }
    return ValUIKitBtn.item(
      child,
          () {
        ValUIKitDialogImpl.closeDialog();
        onTap();
      },
      height: 44.w,
      hasInkWell: false,
      alignment: Alignment.center,
    );
  }
}

class AppbarAttachView extends StatelessWidget {
  const AppbarAttachView(this.config, this.onTapItem, {Key? key, this.width}) : super(key: key);

  final double? width;

  final List<AppbarAttachViewConfig> config;

  final Color bg = const Color(0XFF4C4C4C);

  final ValueChanged<AppbarAttachViewConfig> onTapItem;

  @override
  Widget build(BuildContext context) {
    if (config.isEmpty) return const SizedBox.shrink();
    return Stack(
      alignment: Alignment.topRight,
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(right: 16.w),
          child: Container(width: 10.w, height: 10.w, color: bg, transform: Matrix4.rotationZ(pi / 4)),
        ),
        Container(
          margin: EdgeInsets.only(top: 6.w, right: 10.w),
          decoration: ValUIKitBaseDecoration.getRadius(bg: bg, all: 6.w),
          child: Column(
            children: config.map((e) {
              Widget btn = ValUIKitBtn(
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    ValCommonText.oneLine(e.title, 16,ValUIKitBaseColors.white),
                  ],
                ),
                    () => onTapItem(e),
                hasInkWell: false,
                padding: EdgeInsets.symmetric(vertical: 15.w, horizontal: 20.w),
              );

              return Column(
                children: [
                  Padding(
                    padding: EdgeInsets.only(right: e.padding),
                    child: btn,
                  ),
                  e == config.last
                      ? const SizedBox()
                      : UnconstrainedBox(
                    child: Container(
                      height: 1,
                      color: Colors.white.withOpacity(0.12),
                      width: 85.w,
                    ),
                  ),
                ],
              );
            }).toList(),
          ),
        ),
      ],
    );
  }
}

class AppbarAttachViewConfig {
  final String title;
  final String? icon;
  final String? url;
  final String? tag;
  final double padding;

  AppbarAttachViewConfig({required this.title, this.icon, this.url, this.tag, this.padding = 0});
}
